package com.venusj.springcloud.controller;

import com.venusj.springcloud.entity.Payment;
import com.venusj.springcloud.result.CommonResult;
import com.venusj.springcloud.service.PaymentService;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author zhangjh
 * @date 2020/3/22
 */
@RestController
@Slf4j
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String port;


    @PostMapping(value = "/create")
    public CommonResult create(@RequestBody Payment payment) {
       return paymentService.create(payment);
    }

    @GetMapping(value = "/get/{id}")
    public CommonResult create(@PathVariable("id") Long id) {
        return paymentService.getPaymentById(id);
    }

    @GetMapping(value = "/doscovery")
    public Object doscovery() {
        List<String> services = discoveryClient.getServices();

        for(String element : services) {
            log.info("***element:{}***", element);
        }


        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");

        for (ServiceInstance instance : instances)
        {
            log.info(instance.getServiceId() + "\t" + instance.getHost()
                    + "\t" + instance.getPort() + "\t" +instance.getUri());
        }

        return  this.discoveryClient;
    }


    @GetMapping(value = "/lb")
    public String getPaymentLb() {
        return port;
    }


    @GetMapping(value = "/feign/timeout")
    public String getFeignTimeout() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return port;
    }
}
